//@target illustrator

String.prototype.clearSpace = function(){
  return this.replace(/(^\s*)|(\s*$)/g, "")
}
String.prototype.toAiColor = function(){
  // 支持字符格式为: '100 70 30 0, 128 256 0' 或者 '128 0 0' (rgb 可使用 HEX)
  var colors = this.clearSpace().split(',')
  color = colors[0].hex2rgb().split(' ')
  var isRGBSpace = app.activeDocument.documentColorSpace === DocumentColorSpace.RGB
  if (colors.length === 2 && isRGBSpace) {
    color = colors[1].clearSpace().hex2rgb().split(' ')
  }
  try {
    if(color.length === 3) {
      var newColor = new RGBColor();
      newColor.red = color[0];
      newColor.green = color[1];
      newColor.blue = color[2];
    } else if(color.length === 4) {
      var newColor = new CMYKColor();
      newColor.cyan = color[0];
      newColor.magenta = color[1];
      newColor.yellow = color[2];
      newColor.black = color[3];
    }
    return newColor
  } catch (e) {
    var newColor = new RGBColor();
    newColor.red = 0;
    newColor.green = 0;
    newColor.blue = 0;
  }
  return newColor
}

String.prototype.hex2rgb = function(){
  // '#888' => '128 128 128'
  var sColor = this.toLowerCase();
  //十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 如果是16进制颜色
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = "#";
      for (var i=1; i<4; i+=1) {
        sColorNew += sColor.slice(i, i+1).concat(sColor.slice(i, i+1));
      }
      sColor = sColorNew;
    }
    //处理六位的颜色值
    var sColorChange = [];
    for (var i=1; i<7; i+=2) {
      sColorChange.push(parseInt("0x"+sColor.slice(i, i+2)));
    }
    return sColorChange.join(" ");
  }
  return sColor;
};


var svgCode = '<svg version="1.1" id="jettaVerticalLogo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 106" style="enable-background:new 0 0 100 106;" xml:space="preserve"> <style type="text/css"> .st0{fill:#FFFFFF;} </style> <path class="st0" d="M0.8,5.5C-1,3.3,0.5,0,3.3,0h92.8c3.4,0,5.5,3.6,2.5,7L74.2,34.9c-2.8,3.3-7,5.1-11.3,5.1h-25 c-4.3,0-8.4-1.9-11.3-5.1l-3.5-4C22.7,30.5,23,30,23.4,30h26.4c2.3,0,4.5-1,6-2.7l13.5-15.4c0.6-0.7,0.1-1.8-0.8-1.8H4.8L0.8,5.5z M37,71h-9v-4.5h7v-5h-7V57h8v-5H22v24h15V71z M57,52H41v5h5v19h6V57h5V52z M3.6,57H10v11c0,1.7-1.3,3-3,3H0.9L0,76h9 c3.9,0,7-3.1,7-7V52H4.4L3.6,57z M62,57h5v19h6V57h5v-5H62V57z M100,76h-6l-0.8-4h-6.4L86,76h-6l6-24h8L100,76z M92.2,67L90,56.5 L87.8,67H92.2z M32.3,93.3l-1.3,0.4v-3.4h1.3v-3.6h-1.3v-4.1h-3.6v4.1h-1.8v3.6h1.8v4.5l-1.8,0.5v4.1l1.8-0.5v3.5h-1.1l-0.7,3.6h5.4 v-8.2l1.3-0.4V93.3z M41.7,102.5h6.1l-0.6,3.5l-6.2,0c-1.6,0-3-0.4-4.4-1.1l-1-0.5l-0.3,1.6h-3.2l1.3-7.4h3.2l-0.4,2.1l0.9,0.5 c0.3,0.1,0.5,0.3,0.7,0.4v-0.8v-3.4l-4.3,0v-2.6H38v-1v-0.2h-3.7v-2.4H38v-0.2v-0.9h-4.3v-2.7H38v-1h-4.3v-2.8H38V82h3.6v1.8h5.4 v2.8h-5.4v1h4.9v3.6v0.2h1.1v2.4h-1.1v1.1v2.6h-4.9v1.2h4.9v2.8h-4.9v1.1C41.6,102.5,41.7,102.5,41.7,102.5z M41.6,91.4h1.7v-0.2v-1 h-1.7v1V91.4z M41.6,93.7v0.2v1.1h1.7v-1.1v-0.2H41.6z M58.4,100.7l-0.4-0.3v-9.1h-0.3h-3.4h-2.1v3.4h2.1V99l-2.1,7H56l0.5-1.8 l1.2,0.6c1.4,0.7,2.8,1.1,4.4,1.1l12.1,0l0.7-4H63C60.8,102,59.9,101.5,58.4,100.7z M52.3,84.3l1.3,5.2h3.9l-1.3-5.2H52.3z M64.5,82 v3.8h-0.3h-4.5v3.7h3.4l-3.2,10.6h4.2l2.5-8.5l2.6,8.5h4.2l-3.3-10.6h3.3v-3.7h-5.1h-0.3V82H64.5z"/> </svg> '
var svgGroup = insertSvg(svgCode)
svgGroup.pageItems[0].pathItems[0].fillColor = '90 55 0 0, #285aff'.toAiColor()

function insertSvg(code, color) {
    var svgFileName = "inlineSVGtoAI.svg";
    var svgFile = new File("" + Folder.temp + "/" + svgFileName);
    svgFile.open("w");

    svgFile.write(code);
    svgFile.close();

    var doc = app.activeDocument;
    var placed = doc.groupItems.createFromFile(svgFile);

    $.sleep(500);
    svgFile.remove();

    return placed
}


if (app.documents.length > 0 && app.activeDocument.pathItems.length > 0) {
  var CURR_DOC = app.activeDocument;
  var CURR_ARTBOARD_INDEX = CURR_DOC.artboards.getActiveArtboardIndex()
  var CURR_ARTBOARD = CURR_DOC.artboards[CURR_ARTBOARD_INDEX].artboardRect

  setLogoGroup()
}

/* ============================================================ */
function setLogoGroup() {
  var artboardSize = _getArtboardSize(CURR_ARTBOARD)
  var artboardShortSide = artboardSize.width < artboardSize.height ? artboardSize.width : artboardSize.height
  var logoGroupScaleRatio = getLogoRatio(artboardSize)
  var LOGO_RATIO = 0.526314
  var logoGroupHeight = artboardShortSide * logoGroupScaleRatio
  var distance = logoGroupHeight * LOGO_RATIO
  _setSizeAndPosition({x: artboardSize.x + distance, y: artboardSize.y - distance}, logoGroupHeight)
}

function getLogoRatio(rectangle) {
    var ratioRange =  [1,    4/3,  7/5,  3/2,  16/9, 2,   3,   5,   9,   10];
    var logoRatios = [[0.4,  0.4,  0.4,  0.4,  0.4,  0.4, 0.4, 0.4, 0.4, 0.4],
                      [0.15, 0.15, 0.15, 0.15, 0.15, 0.2, 0.2, 0.3, 0.3, 0.4],
                      [0.15, 0.15, 0.15, 0.15, 0.15, 0.2, 0.2, 0.3, 0.3, 0.4]]
    var W = rectangle.width || 1;
    var H = rectangle.height || 1;
    var rectRatio = W > H ? W / H : H / W;
    var ratioIndex = _getArrIndex_(ratioRange, rectRatio) - 1
    var typesRange = [130, 560]
    var shortSide = W < H ? W : H;
    var typeIndex = _getArrIndex_(typesRange, shortSide)
    return logoRatios[typeIndex][ratioIndex]
}

/* ================== Public Base Function ========================================== */

// functions
// setSizeAndPosition({x: -100, y: 200}, 100)
/* todo 默认以px为单位，需要增加单位判断 */
function _setSizeAndPosition (position, height) {
  var doc = app.activeDocument;
  if (doc.selection.length < 1) {
    alert(':-) 请选好图形后，再试试')
    return
  }
  var curr = doc.selection[0]
  var ratio = curr.width / curr.height || 1

  if  (position) {
    curr.left = position.x
    curr.top = position.y
  }
  if (height) {
    curr.height = height * 105.96 / 76
    curr.width = curr.height * ratio
  }
}

function _getArtboardSize(canvas) {
    var rect = canvas.toString().split(',')
    var x1 = +rect[0]
    var y1 = +rect[1]
    var x2 = +rect[2]
    var y2 = +rect[3]
    var rectangle = {
        y: y1,
        x: x1,
        width: Math.abs(x2 - x1),
        height: Math.abs(y2 - y1)
    }
    return rectangle
}

/* ================== Js untis Functions ========================================== */

function _getArrIndex_(arr, num) {
  var index = 0;
  var len = arr.length
  if (num >= arr[len - 1]) {
    return len
  }
	while(arr[index] <= num) {
		index += 1;
	}
	return index;
}
